package com.gsy.iit;

import com.gsy.gsy_common_util.fileUtil.FileUtils;
import com.mysql.cj.CoreSession;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.*;

public class CourseAnalysis {
    /**
     * 类加载时就加载这个方法，然后加载到静态对象中
     */
    static HashMap<String,String> csTeacher = new HashMap<>();
    static HashMap<String,String> eceTeacher = new HashMap<>();
    static {
        for (Degree value : Degree.values()) {
            value.setCourse(getCourses(value));
        }
        try {
//            try {
//                Class.forName("com.mysql.cj.jdbc.Driver");
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            }
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spider","root","password");
            String sql = "select t.name,t.describe from teacher t where type=?";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1,"cs");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
//                System.out.println(1);
                csTeacher.put(resultSet.getString(1),resultSet.getString(2));
            }
            preparedStatement.setString(1,"ece");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                eceTeacher.put(resultSet.getString(1),resultSet.getString(2));
            }
            preparedStatement.close();
            conn.close();



        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public static void main(String[] args) {
//        System.out.println(csTeacher.size());
//        System.out.println(Degree.CS.getCourse().values().iterator().next().toCsvString());
        HashMap<String,ArrayList<String>> keywordHashmap = getKeywordMap();
        HashMap<String,ArrayList<String>> keywordHashmap1 = new HashMap<>();
        keywordHashmap1.put("自然语言处理 NLP",keywordHashmap.get("自然语言处理 NLP"));

        for (Map.Entry<String, ArrayList<String>> keywordEntry : keywordHashmap1.entrySet()) {
            HashSet<String> hashSet = new HashSet<>();
            StringBuilder stringBuilder = new StringBuilder();
//            byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
            stringBuilder.append("\ufeff");
//            stringBuilder.append("\n");
            stringBuilder.append(keywordEntry.getKey()+"\n");
            stringBuilder.append("课程代号,课程名,课程简介\n");
            stringBuilder.append("cs课程\n");
            for (String keyword : keywordEntry.getValue()) {
                for (Map.Entry<String, Course> courseEntry : Degree.CS.getCourse().entrySet()) {
                    if (courseEntry.getValue().getCourseName().toLowerCase().contains(keyword.toLowerCase()) && !hashSet.contains(courseEntry.getKey()) && hashSet.size() < 10){
                        stringBuilder.append(courseEntry.getValue().toCsvString());
                        hashSet.add(courseEntry.getKey());
                    }
                }
            }
            for (String keyword : keywordEntry.getValue()) {
                for (Map.Entry<String, Course> courseEntry : Degree.CS.getCourse().entrySet()) {
                    if (courseEntry.getValue().getCourseDescription().toLowerCase().contains(keyword.toLowerCase()) && !hashSet.contains(courseEntry.getKey()) && hashSet.size() < 10){
                        stringBuilder.append(courseEntry.getValue().toCsvString());
                        hashSet.add(courseEntry.getKey());
                    }
                }
            }
            hashSet.clear();
            stringBuilder.append("ece课程\n");
            for (String keyword : keywordEntry.getValue()) {
                for (Map.Entry<String, Course> courseEntry : Degree.ECE.getCourse().entrySet()) {
                    if (courseEntry.getValue().getCourseName().toLowerCase().contains(keyword.toLowerCase()) && !hashSet.contains(courseEntry.getKey()) && hashSet.size() < 10){
                        stringBuilder.append(courseEntry.getValue().toCsvString());
                        hashSet.add(courseEntry.getKey());
                    }
                }
            }
            for (String keyword : keywordEntry.getValue()) {
                for (Map.Entry<String, Course> courseEntry : Degree.ECE.getCourse().entrySet()) {
                    if (courseEntry.getValue().getCourseDescription().toLowerCase().contains(keyword.toLowerCase()) && !hashSet.contains(courseEntry.getKey()) && hashSet.size() < 10){
                        stringBuilder.append(courseEntry.getValue().toCsvString());
                        hashSet.add(courseEntry.getKey());
                    }
                }
            }
            stringBuilder.append("\n\ncs教授\n");
            hashSet.clear();
            for (String keyword : keywordEntry.getValue()) {
                for (Map.Entry<String, String> teacherEntry : csTeacher.entrySet()) {
                    if (teacherEntry.getValue().toLowerCase().contains(keyword.toLowerCase()) && !hashSet.contains(teacherEntry.getKey())){
                        stringBuilder.append("\""+teacherEntry.getKey()+"\",\""+teacherEntry.getValue().replaceAll("\n",". ").replaceAll("\"","''")+"\"\n");
                        hashSet.add(teacherEntry.getKey());
                    }
                }
            }
            stringBuilder.append("\n\nece教授\n");
            hashSet.clear();
            for (String keyword : keywordEntry.getValue()) {
                for (Map.Entry<String, String> teacherEntry : eceTeacher.entrySet()) {
                    if (teacherEntry.getValue().toLowerCase().contains(keyword.toLowerCase()) && !hashSet.contains(teacherEntry.getKey())){
                        stringBuilder.append("\""+teacherEntry.getKey()+"\",\""+teacherEntry.getValue().replaceAll("\n",". ").replaceAll("\"","''")+"\"\n");
                        hashSet.add(teacherEntry.getKey());
                    }
                }
            }
            
            try {
                FileUtils.stringToFile(stringBuilder.toString(),"D:\\Michael",keywordEntry.getKey()+".csv","utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }


        }


    }

    public static HashMap<String,ArrayList<String>> getKeywordMap(){
        //这一步做完是保证了课程的筛选关键词，然后还有什么实验室之类的东西，我到时候看看吧。
        //实验室，师资介绍，该方向的亮点，知名企业，有点无聊
        HashMap<String,ArrayList<String>> hashMap = new HashMap<>(){
            {
                put("人工智能",new ArrayList<>(Arrays.asList("artificial","knowledge ","machine learning","Neural","agent","probabilistic","logical","cluster","vision","human","deep learning")));
                put("机器学习",new ArrayList<>(Arrays.asList("artificial","knowledge ","machine learning","Neural","agent","probabilistic","logical","cluster","vision","human","deep learning")));
                put("深度学习",new ArrayList<>(Arrays.asList("artificial","knowledge ","machine learning","Neural","agent","probabilistic","logical","cluster","vision","human","deep learning")));
                put("神经网络",new ArrayList<>(Arrays.asList("artificial","knowledge ","machine learning","Neural","agent","probabilistic","logical","cluster","vision","human","deep learning")));
                put("自动驾驶",new ArrayList<>(Arrays.asList("artificial","knowledge ","machine learning","Neural","agent","probabilistic","logical","cluster","vision")));
                put("计算机视觉 CV",new ArrayList<>(Arrays.asList("artificial","knowledge ","learning ","Neural","agent","probabilistic","logical","cluster","vision")));
                put("自然语言处理 NLP",new ArrayList<>(Arrays.asList("nlp","Deep","artificial","knowledge ","learning ","Neural","agent","probabilistic","logical","cluster","vision","nlp","human")));
                put("机器人",new ArrayList<>(Arrays.asList("artificial","knowledge ","learning ","Neural","agent","probabilistic","logical","cluster","vision","nlp","human","robot")));
                put("云计算",new ArrayList<>(Arrays.asList("cloud","parallel","Networks","Distributed","social network")));
                put("物联网",new ArrayList<>(Arrays.asList("cloud","parallel","Networks","Distributed","social network","embed","VLSI","operating")));
                put("5G",new ArrayList<>(Arrays.asList("5G","Wireless")));
                put("芯片、集成电路设计",new ArrayList<>(Arrays.asList("Chip, integrated circuit design, ASIC, VLSI, Application Specific Integrated Circuit, IC Simulation, IC, integrated circuit, Sequential Logic Circuit Design, VLSI Design, VLSI, Very Large Scale Integration, Static Timing Analysis, chip level planning, soc".split(", "))));
                put("网络、计算机网络",new ArrayList<>(Arrays.asList("Network, computer network, tcp, ip protocol, ip address, router, gateway, firewall, http, udp, wireless".split(", "))));
                put("并行计算，高性能计算",new ArrayList<>(Arrays.asList("Parallel computing, Parallel, CUDA, serial execution, parallel execution, pipelining, symmetric multi-processor, observed speedup, parallel overhead, cluster computing, openmp, posix, mpi, pvm, hpf, nhbl, High performance computing, Parallel".split(", "))));
                put("数据库",new ArrayList<>(Arrays.asList("database, dbms, acid, mybatis, SQL, RDBMS, DBS, DBA, Oracle, Hadoop".split(", "))));
                put("slam",new ArrayList<>(Arrays.asList("SLAM, RGB-D SLAM, Simultaneous Localization and Mapping, sparse mapping, dense mapping, vision".split(", "))));
                put("VR、AR、虚拟现实、增强现实",new ArrayList<>(Arrays.asList("vr, virtual reality, augmented reality".split(", "))));
                put("脑机接口",new ArrayList<>(Arrays.asList("Brain computer interface".split(", "))));
                put("区块链",new ArrayList<>(Arrays.asList("block chain, blockchain, altcoin, AML, Anti Money Laundering, ASIC Miner, Atomic Swap, Bitcoin Improvement Protocol, Block Height, Block Reward, CryptoCurrency, DDoS, Deep/Dark Web, MicroTransaction".split(", "))));
            }
        };
        return hashMap;

    }

    public static String getCoursePrerequisites(String s){
        s = s.toUpperCase();
        Degree degree = Degree.valueOf(s.substring(0,s.charAt(' ')));
        ArrayList<ArrayList<String>> req = degree.getCourse().get(s).getCoursePrerequisite();
        StringBuffer stringBuffer = new StringBuffer();
        for (ArrayList<String> strings : req) {
//            System.out.println(strings);
            stringBuffer.append(strings.toString());
            stringBuffer.append("\n");
        }
        return stringBuffer.toString();
    }
    public static String getCoursePrerequisites(String s,Degree degree,int newLine){
//        System.out.println(degree.getCourse().size());
//        s = s.substring(s.length()-3);
        StringBuffer stringBuffer = new StringBuffer();
        Course course = degree.getCourse().get(s);
        if (course == null || course.getCoursePrerequisite() == null){
            return "";
        }
        for (ArrayList<String> strings : course.getCoursePrerequisite()) {
            for (String string : strings) {
//                System.out.print(string+",");
                stringBuffer.append(string);
                stringBuffer.append(",");
                stringBuffer.append(getCoursePrerequisites(string,degree,0));
            }
            if (newLine == 1){
                stringBuffer.append("\n");
            }
        }
        return stringBuffer.toString();
    }
    /**
     * 枚举类型作为参数，返回一个course的list。
     * @param name
     * @return
     */
    public static HashMap<String,Course> getCourses(Degree name){
        HashMap<String,Course> hashMap = new HashMap<>();
        try {
            //读取resources目录下文件的方式，不太明白道理
            String s = FileUtils.fileToString(new File(CourseAnalysis.class.getClassLoader().getResource(name.getName()).getPath()));

            Document document = Jsoup.parse(s);
            Elements elements = document.getElementsByClass("courseblock");

            for (int i = 0; i < elements.size(); i++) {
                Course course = new Course();
                course.setCourseCode(elements.get(i).getElementsByClass("noindent coursecode").first().text());
                course.setCourseName(elements.get(i).getElementsByClass("noindent coursetitle").first().text());
                Elements temp = elements.get(i).children();
                course.setCourseDescription(temp.get(1).text());
                for (int j = 2; j < temp.size(); j++) {
                    String ss = temp.get(j).text();
                    if (ss.matches("Prerequisite.*")){
                        ss = ss.replaceAll("Prerequisite[(]s[)]:","");
                        String[] sarr = ss.split("or");
                        ArrayList<ArrayList<String>> arrayLists = new ArrayList<>();
                        for (int i1 = 0; i1 < sarr.length; i1++) {
                            ArrayList<String> arrayList1 = new ArrayList<>();
                            String[] andArr = sarr[i1].split("and");
                            for (String s1 : andArr) {
//                                arrayList1.add(s1.strip().replaceAll(".*((CS|MATH|ECE|COM|ITMD|ITMO|ITM) \\d{3}).*","$1"));
                                arrayList1.add(s1.strip().replaceAll("[(]?([A-Z]{2,4} \\d{3}).*","$1"));
                            }
                            arrayLists.add(arrayList1);
                        }
                        course.setCoursePrerequisite(arrayLists);
                    }
                }
                hashMap.put(course.getCourseCode(),course);
            }
            return hashMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
